<?php
/*
 * @Description    : 邮件发送
 * @Author         : QianLong
 * @Date           : 2023-01-11 12:13:55
 * @LastEditors    : QianLong
 * @Site           : http://21ds.cn
 * @LastEditTime   : 2023-09-26 15:47:07
 */

declare(strict_types=1);

namespace App\Controller;

use App\Common\RedisCache;
use App\Constants\Status;
use App\Exception\ApiException;
use App\Job\SendEmailJob;
use App\Job\SignFailAddJob;
use App\Job\SymfonyEmailDataJob;
use App\Job\SymfonyEmailJob;
use App\Service\Common;
use Qianlong\Validate\Validate;

class EmailController extends AbstractController
{
  public function send2()
  {
    $ulid = (new \Hidehalo\Nanoid\Client())->formattedId('0123456789abcdefghijklmnopqrstuvwxyz_');
    return $this->response->json(Status::CODE_FAIL, 'test', $ulid);
    $valitor = new Validate();
    $valitor->addColumn('es_id')->required();
    $valitor->addColumn('et_id')->optional();
    $valitor->addColumn('content')->required();
    $valitor->addColumn('email')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $emailList = explode(',', $param['email']);
    $userInfo = $this->dataResource->getUserInfo();
    $redisCache = new RedisCache;
    $emailSetting = $redisCache->getEmailSetting($userInfo['uid']);
    if ($emailSetting['ip_limit'] == 1 && !empty($emailSetting['server_ip'])) {
      $remoteIp = $this->dataResource->getClientIp($this->request);
      $sysSetting = $redisCache->getSysSetting();
      $allIp = $sysSetting['server_ip'].','. $emailSetting['server_ip'];
      $server_ip = explode(',', $allIp);
      $is_local = filter_var($remoteIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
      if (!in_array($remoteIp, $server_ip) && $is_local != false) {
        return $this->response->json(Status::CODE_FAIL, 'IP不在可信范围内', []);
      }
    }
    if (count($emailList) > 500) {
      return $this->response->json(Status::CODE_FAIL, '单次最多可传入500个邮箱', []);
    }
    if (isset($param['is_filter']) && $param['is_filter'] == 1 && empty($param['filter_id'])) {
      return $this->response->json(Status::CODE_FAIL, '开启过滤后，filter_id为必填项', []);
    }
    $param['uid'] = (int)$userInfo['uid'];
    queue_push(new SendEmailJob($param));
    return $this->response->json(Status::CODE_OK, '任务下发成功，请稍后查看发送日志', []);
  }
  public function send()
  {
    $valitor = new Validate();
    $valitor->addColumn('es_id')->required();
    $valitor->addColumn('et_id')->optional();
    $valitor->addColumn('content')->required();
    $valitor->addColumn('email')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $emailList = explode(',', $param['email']);
    $userInfo = $this->dataResource->getUserInfo();
    $redisCache = new RedisCache;
    $emailSetting = $redisCache->getEmailSetting($userInfo['uid']);
    if ($emailSetting['ip_limit'] == 1 && !empty($emailSetting['server_ip'])) {
      $remoteIp = $this->dataResource->getClientIp($this->request);
      $sysSetting = $redisCache->getSysSetting();
      $allIp = $sysSetting['server_ip'].','. $emailSetting['server_ip'];
      $server_ip = explode(',', $allIp);
      $is_local = filter_var($remoteIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
      if (!in_array($remoteIp, $server_ip) && $is_local != false) {
        return $this->response->json(Status::CODE_FAIL, 'IP不在可信范围内', []);
      }
    }
    if (count($emailList) > 1000) {
      return $this->response->json(Status::CODE_FAIL, '单次最多可传入1000个邮箱', []);
    }
    if (isset($param['is_filter']) && $param['is_filter'] == 1 && empty($param['filter_id'])) {
      return $this->response->json(Status::CODE_FAIL, '开启过滤后，filter_id为必填项', []);
    }
    $serverInfo = $redisCache->getEmailServer($param['es_id']);
    $newSign = (new \App\Service\Common)->devSignGeneral($param, $serverInfo['server_secret']);
    $newSign2 = (new \App\Service\Common)->generateSignature($param, $serverInfo['server_secret']);
    if ($param['sign'] != $newSign && $param['sign'] != $newSign2['sign']) {
      $logData['url'] = $this->request->fullUrl();
      $logData['remoteIp'] = $remoteIp;
      $logData['user_sign'] = $param['sign'];
      $logData['server_sign'] = $newSign2['sign'];
      $logData['server_query'] = $newSign2['query'];
      $logData['uid'] = $serverInfo['uid'];
      queue_push(new SignFailAddJob($logData));
      return $this->response->json(Status::CODE_FAIL, 'sign签名校验失败');
    }
    if ($serverInfo['status'] != 1) {
      return $this->response->json(Status::CODE_FAIL, '当前配置状态不可用，如需使用，请登录柠聚开发平台启用后重试', []);
    }
    $param['uid'] = (int)$userInfo['uid'];
    queue_push(new SymfonyEmailDataJob($param));
    return $this->response->json(Status::CODE_OK, '任务下发成功，请稍后查看发送日志', []);
  }
  public function getCate()
  {
    $valitor = new Validate();
    $valitor->addColumn('cate_id')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $where['cate_id'] = $param['cate_id'];
    $where['status'] = 1;
    $hasLog = mongodb2()->email_tpl_list->find($where);
    $returnD = [];
    foreach ($hasLog as $key => $vo) {
      $item['_id'] = $vo['_id'];
      $item['title'] = $vo['title'];
      $returnD[] = $item;
    }
    return $this->response->json(Status::CODE_OK, 'success', $returnD);
  }
  public function img()
  {
    $param = $this->request->all();
    $uid = 1;
    if (substr($param['send_id'], 0, 3) !== 'ESL') {
      $dencryptData = (new Common)->decryptDevKEY($param['send_id']);
      $dencryptData = json_decode($dencryptData,true);
      $param['send_id'] = $dencryptData['id'];
      $uid = $dencryptData['uid'];
    }
    $where['_id'] = $param['send_id'];
    $collection = mongodb2()->selectCollection('send_email_log_' . $uid);
    $hasLog = $collection->findOne($where);
    $hasLog = json_decode(json_encode($hasLog), true);
    if (!empty($hasLog) && $hasLog['is_read'] != 1) {
      $collection->updateOne($where, ['$set' => ['is_read' => 1, 'read_time' => time()]]);
    }
    $pic = file_get_contents(BASE_PATH . '/static/empty.png');
    return $this->response->png($pic);
  }
}
